package com.wpf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpf.system.common.utils.MakeTree;
import com.wpf.system.entity.*;
import com.wpf.system.entity.vo.CascaderVO;
import com.wpf.system.service.DepartmentService;
import com.wpf.system.mapper.DepartmentMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author ferna
* @description 针对表【department(部门班级表（学院->专业/部门->班级）)】的数据库操作Service实现
* @createDate 2022-12-15 22:31:17
*/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService{

    @Override
    public List<Department> getDeptList() {
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Department::getSort);
        List<Department> deptList = this.baseMapper.selectList(queryWrapper);
        List<Department> deptListTree = MakeTree.makeDeptTree(deptList,0L);
        return deptListTree;
    }

    @Override
    public List<CascaderVO> getParentDeptList() {
        String[] type = {"0","1"};
        List<String> typeList = Arrays.asList(type);
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Department::getType,typeList).orderByAsc(Department::getSort);
        List<Department> deptList = this.baseMapper.selectList(queryWrapper);
        List<CascaderVO> CascaderListTree = MakeTree.makeDeptCascader(deptList,0L);
        return CascaderListTree;
    }

    @Override
    public int deleteDeptById(Long id) {
        ArrayList<Long> ids = new ArrayList<>();
        //先把要删除的一级分类id放入到集合中
        ids.add(id);
        //递归的将一级分类下的id也加入到集合中
        this.getIds(ids,id);
        //批量删除集合中的id
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public List<Long> getDeptIdByPid(Long id) {
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        this.getIds(ids,id);
        return ids;
    }

    public void getIds(ArrayList<Long> ids, Long oneId) {
        //查询二级分类的对象
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Department::getPid,oneId);
        List<Department> childrenList = baseMapper.selectList(queryWrapper);
        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (Department children : childrenList) {
            Long id = children.getId();
            ids.add(id);
            //把二级分类的每一个ID，查询它下面的子节点
            this.getIds(ids,id);
        }
    }
}




